<template>
	<div class="container">
		<div class="el-card is-always-shadow diygw-col-24">
			<div class="el-card__body">
				<div class="mb8">
					<el-form class="flex flex-direction-row flex-wrap" :model="queryParams" :rules="queryParamsRules" ref="queryForm" label-width="80px">
						<div class="flex diygw-col-0">
							<el-form-item class="diygw-el-rate" prop="body_like" label="标题">
								<el-input type="text" placeholder="请输入标题查询" v-model="queryParams.body_like"> </el-input>
							</el-form-item>
						</div>
						<div class="flex diygw-col-0">
							<el-form-item prop="status" class="diygw-el-rate" label="订单状态">
								<el-select clear-icon="CircleClose" suffix-icon="ArrowUp" placeholder="请选择" v-model="queryParams.status" style="width: 100% !important">
									<el-option v-for="item in statusDatas" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-form-item>
						</div>
						<div class="flex diygw-col-0">
							<el-button type="primary" @click="handleQuery"> <SvgIcon name="ele-Search" /> 搜索 </el-button> <el-button @click="resetQuery"> <SvgIcon name="ele-Refresh" /> 重置 </el-button>
						</div>
					</el-form>
				</div>
				<el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" stripe border current-row-key="id" empty-text="没有数据" style="width: 100%">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column label="标题" prop="title" align="center"> </el-table-column>
					<el-table-column label="收货人" prop="username" align="center"> </el-table-column>
					<el-table-column label="电话" prop="phone" align="center"> </el-table-column>
					<el-table-column label="数据状态" prop="status" align="center">
						<template #default="scope"> <dict-tag :options="statusDatas" :value="scope.row.status" valueField="value" labelField="label" /> </template>
					</el-table-column>
					<el-table-column label="备注" prop="remark" align="center"> </el-table-column>
					<el-table-column label="操作" prop="remark" align="center">
						<template #default="scope"> <el-tag style="cursor: pointer; margin-right: 5px" v-if="scope.row.payStatus == 1 && scope.row.status >= 1" type="error" @click="deliveryFunction(scope.row)"> 发货 </el-tag><el-tag style="cursor: pointer" type="info" @click="viewFunction(scope.row)"> 查看 </el-tag> </template>
					</el-table-column>
				</el-table>
				<!-- 分页设置-->
				<div v-show="total > 0"><el-divider></el-divider> <el-pagination background :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" /></div>
			</div>
			<!-- 添加或修改参数配置对话框 -->
			<el-dialog :fullscreen="isFullscreen" width="1000px" v-model="isShowDialog" destroy-on-close title="订单" draggable center>
				<template #header="{ close, titleId, titleClass }">
					<h4 :id="titleId" :class="titleClass">订单</h4>
					<el-tooltip v-if="!isFullscreen" content="最大化" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<FullScreen />
							</el-icon>
						</el-button>
					</el-tooltip>
					<el-tooltip v-if="isFullscreen" content="返回" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<Remove />
							</el-icon>
						</el-button>
					</el-tooltip>
				</template>
				<el-form class="flex flex-direction-row flex-wrap" :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px"> </el-form>
				<template #footer>
					<div class="dialog-footer flex justify-center"><el-button @click="closeDialog"> 取 消 </el-button> <el-button type="primary" @click="onSubmit" :loading="saveloading"> 保 存 </el-button></div>
				</template>
			</el-dialog>
		</div>
		<el-dialog :title="form.isedit ? '发货' : '查看'" width="1000px" v-model="dialog" class="" modal close-on-click-modal close-on-press-escape show-close>
			<div class="flex diygw-col-24 flex-wrap">
				<el-form ref="formRef" :model="form" label-width="90px" label-postition="right" class="flex flex-wrap diygw-col-24">
					<div class="flex flex-wrap diygw-col-24 items-center flex-clz">
						<div class="flex diygw-col-12 items-center flex-nowrap">
							<span class="diygw-col-0 text4-clz"> 订单号 </span>
							<span class="diygw-col-0">
								{{ form.orderNo }}
							</span>
						</div>
						<div class="flex diygw-col-6 items-center flex-nowrap">
							<span class="diygw-col-0 text2-clz"> 下单时间 </span>
							<span class="diygw-col-0">
								{{ form.createTime }}
							</span>
						</div>
						<div class="flex diygw-col-6 items-center flex-nowrap">
							<span class="diygw-col-0 text6-clz"> 订单状态 </span>
							<div class="diygw-col-0">
								<dict-tag :options="statusDatas" :value="form.status" valueField="value" labelField="label" />
							</div>
						</div>
					</div>
					<div class="flex flex-wrap diygw-col-24 items-center flex3-clz">
						<div class="flex diygw-col-24 items-center flex-nowrap">
							<span class="diygw-col-0 text-clz"> 收货地址 </span> <span class="diygw-col-0"> {{ form.body.address.title }}-{{ form.body.address.phone }} -{{ form.body.address.provinceLabel }}-{{ form.body.address.address }} </span>
						</div>
					</div>
					<div class="flex flex-wrap diygw-col-24 items-center flex7-clz">
						<div class="flex diygw-col-24 items-center flex-nowrap">
							<span class="diygw-col-0 text8-clz"> 产品明细 </span>
							<div v-for="(item, index) in form.body.carts" :key="index" class="flex diygw-col-24 items-stretch flex-nowrap flex10-clz">
								<div class="flex diygw-col-0 image-clz"><el-image :src="item.img" fit="fill" style="height: 60px; width: 60px" /></div>
								<div class="flex diygw-col-24 flex-direction-column justify-between items-center flex-wrap flex11-clz">
									<span class="diygw-col-24">
										{{ item.title }}
									</span>
									<span class="diygw-col-24"> {{ item.price }} * {{ item.number }} = {{ item.title }} </span>
								</div>
							</div>
						</div>
					</div>
					<div class="flex flex-wrap diygw-col-24 items-center flex9-clz">
						<div class="flex diygw-col-24 items-center flex-nowrap">
							<span class="diygw-col-0 text9-clz"> 合计 </span>
							<span class="diygw-col-0">
								{{ form.total }}
							</span>
						</div>
					</div>
					<div v-if="!form.isedit" class="flex flex-wrap diygw-col-24 items-center flex13-clz">
						<div class="flex diygw-col-12 items-center flex-nowrap">
							<span class="diygw-col-0 text11-clz"> 配送方式 </span>
							<span class="diygw-col-0">
								{{ form.deliveryType }}
							</span>
						</div>
						<div class="flex diygw-col-12 items-center flex-nowrap">
							<span class="diygw-col-0 text15-clz"> 配送单号 </span>
							<span class="diygw-col-0">
								{{ form.deliveryCode }}
							</span>
						</div>
					</div>
					<div v-if="form.isedit" class="flex diygw-col-24">
						<el-form-item class="diygw-el-rate" prop="deliveryType" label="配送方式">
							<el-input type="text" placeholder="请输入提示" v-model="form.deliveryType"> </el-input>
						</el-form-item>
					</div>
					<div v-if="form.isedit" class="flex diygw-col-24">
						<el-form-item class="diygw-el-rate" prop="deliveryCode" label="配送单号">
							<el-input type="text" placeholder="请输入配送单号或快递单号" v-model="form.deliveryCode"> </el-input>
						</el-form-item>
					</div>
					<div v-if="form.isedit && (form.status == 1 || form.status == 2)" class="flex diygw-col-24">
						<el-form-item prop="statusType" class="diygw-el-rate" label="是否发货">
							<el-radio-group v-model="form.statusType">
								<el-radio v-for="item in formData.statusTypeDatas" :key="item.value" :label="item.value">
									{{ item.label }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</div>
					<div class="flex flex-wrap diygw-col-24 justify-center flex6-clz">
						<div v-if="!form.isedit" class="flex diygw-col-0 button-clz"><el-button native-type="button" @click="dialog = false" type="danger"> 关闭 </el-button></div>
						<div v-if="form.isedit" class="flex diygw-col-0 button2-clz"><el-button native-type="button" @click="dialog = false" type="danger"> 取消 </el-button></div>
						<div v-if="form.isedit" class="flex diygw-col-0 button1-clz"><el-button native-type="button" :loading="saveFormLoading" @click="submitForm" type="primary"> 提交 </el-button></div>
					</div>
				</el-form>
			</div>
			<div class="clearfix"></div>
		</el-dialog>
		<div class="clearfix"></div>
	</div>
</template>

<script>
	import { useRouter, useRoute } from 'vue-router';
	import { storeToRefs } from 'pinia';
	import { useUserInfo } from '@/stores/userInfo';

	import { ElMessageBox, ElMessage } from 'element-plus';
	import { deepClone, changeRowToForm } from '@/utils/other';
	import { addData, updateData, delData, listData, postData } from '@/api';

	export default {
		components: {},
		data() {
			return {
				globalOption: {},
				userInfo: {},
				ordernum: {
					code: 200,
					msg: '设置成功'
				},
				updatenum: {
					code: 200,
					msg: '修改成功',
					data: {
						id: '1',
						sortnum: '0'
					}
				},
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 弹出层标题
				title: '',
				// 总条数
				total: 0,
				tableData: [],
				statusDatas: [
					{ value: '', label: '全部', elTagType: 'info' },
					{ value: '0', label: '未支付', elTagType: 'danger' },
					{ value: '1', label: '待发货', elTagType: 'success' },
					{ value: '2', label: '待收货', elTagType: 'warning' },
					{ value: '3', label: '已完成', elTagType: 'primary' },
					{ value: '4', label: '已关闭', elTagType: 'info' }
				],
				// 是否显示弹出层
				isFullscreen: false,
				isShowDialog: false,
				saveloading: false,
				editFormInit: {},
				queryParamsInit: {},
				dialog: false,
				saveFormLoading: false,

				form: {
					deliveryType: '',
					deliveryCode: '',
					statusType: '0'
				},

				queryParams: {
					pageNum: 1,
					pageSize: 10,
					body_like: '',
					status: ''
				},

				queryParamsRules: {},

				editForm: {
					id: undefined
				},

				formData: {
					statusTypeDatas: [
						{ value: '0', label: '否' },
						{ value: '1', label: '是' }
					]
				},

				editFormRules: {}
			};
		},
		methods: {
			getParamData(e, row) {
				row = row || {};
				let dataset = e.currentTarget ? e.currentTarget.dataset : e;
				if (row) {
					dataset = Object.assign(dataset, row);
				}
				return dataset;
			},
			navigateTo(e, row) {
				let dataset = this.getParamData(e, row);
				let { type } = dataset;
				if (type == 'page' || type == 'inner' || type == 'href') {
					this.router.push({
						path: dataset.url,
						query: dataset
					});
				} else if (typeof this[type] == 'function') {
					this[type](dataset);
				} else {
					ElMessage.error('待实现点击事件');
				}
			},
			async init() {},
			// 置顶 API请求方法
			async ordernumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/cms/notice/sortnum';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				let flag = await this.confirmFunction({ title: '确定置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let ordernum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.ordernum = ordernum;
				this.resetQuery();
			},
			// 设置为0 API请求方法
			async updatenumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/cms/notice/update';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				http_data.sortnum = 0;
				let flag = await this.confirmFunction({ title: '确定取消置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let updatenum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.updatenum = updatenum;
				this.resetQuery();
			},

			// confirm 自定义方法
			async confirmFunction(param) {
				param = param || {};
				let thiz = this;
				let title = param && (param.title || param.title == 0) ? param.title : thiz.title || '';
				return new Promise((resolve) => {
					ElMessageBox({
						message: title,
						title: '警告',
						showCancelButton: true,
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							resolve(true);
						})
						.catch(() => {
							resolve(false);
						});
				});
			},

			// delivery 自定义方法
			async deliveryFunction(param) {
				param = param || {};
				let thiz = this;
				this.form = param;
				if (param.status == 1) {
					this.form.statusType = '0';
				} else {
					this.form.statusType = '1';
				}
				//用于编辑
				this.form.isedit = true;
				this.dialog = true;
			},

			// view 自定义方法
			async viewFunction(param) {
				param = param || {};
				let thiz = this;
				this.form = param;
				this.form.isedit = false;
				this.dialog = true;
			},
			// 打开弹窗
			openDialog(row) {
				if (row.id && row.id != undefined && row.id != 0) {
					this.editForm = changeRowToForm(row, this.editForm);
				} else {
					this.initForm();
				}
				this.isShowDialog = true;
				this.saveloading = false;
			},

			// 关闭弹窗
			closeDialog(row) {
				this.mittBus.emit('onEditAdmintableModule', row);
				this.isShowDialog = false;
			},

			// 保存
			onSubmit() {
				const formWrap = this.$refs.editFormRef;
				if (!formWrap) return;
				formWrap.validate((valid, fields) => {
					if (valid) {
						this.saveloading = true;
						if (this.editForm.status == 1 && this.editForm.payStaus == 1) {
							if (this.editForm.deliveryType) {
							}
						}
						if (this.editForm.id != undefined && this.editForm.id != 0) {
							updateData('/shop/order', this.editForm)
								.then(() => {
									ElMessage.success('修改成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						} else {
							addData('/shop/order', this.editForm)
								.then(() => {
									ElMessage.success('新增成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						}
					} else {
						let message = '';
						if (fields && Object.keys(fields).length > 0) {
							let field = fields[Object.keys(fields)[0]];
							let messages = field.map((item) => {
								return item.message;
							});
							message = messages.join(',');
						}
						ElMessage.error('验证未通过！' + message);
					}
				});
			},
			// 表单初始化，方法：`resetFields()` 无法使用
			initForm() {
				this.editForm = deepClone(this.editFormInit);
			},
			/** 查询订单列表 */
			handleQuery() {
				this.loading = true;
				listData('/shop/order', this.queryParams).then((response) => {
					response.rows.forEach((item) => {
						item.body = JSON.parse(item.body);
						item.username = item.body.address.title;
						item.phone = item.body.address.phone;
					});
					this.tableData = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.queryParams = deepClone(this.queryParamsInit);
				this.handleQuery();
			},

			// 打开新增订单弹窗
			onOpenAddModule(row) {
				row = [];
				this.title = '添加订单';
				this.openDialog(row);
			},
			// 打开编辑订单弹窗
			onOpenEditModule(row) {
				this.title = '修改订单';
				this.initForm();
				this.openDialog(row);
			},
			/** 删除按钮操作 */
			onTabelRowDel(row) {
				let thiz = this;
				const id = row.id || this.ids;
				ElMessageBox({
					message: '是否确认删除选中的订单?',
					title: '警告',
					showCancelButton: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					return delData('/shop/order', id).then(() => {
						thiz.handleQuery();
						ElMessage.success('删除成功');
					});
				});
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id);
				this.single = selection.length != 1;
				this.multiple = !selection.length;
			},

			//分页页面大小发生变化
			handleSizeChange(val) {
				this.queryParams.pageSize = val;
				this.handleQuery();
			},
			//当前页码发生变化
			handleCurrentChange(val) {
				this.queryParams.pageNum = val;
				this.handleQuery();
			},
			submitForm() {
				if (!this.$refs.formRef) return;
				this.$refs.formRef.validate((valid, fields) => {
					if (valid) {
						this.saveFormLoading = true;
						let param = this.form;
						let url = '/shop/order/update';
						//如果是已发货
						if (param.statusType == '1') {
							//修改为已发货
							param.status = '2';
						} else if (param.status == '2') {
							//修改为未发货
							param.status = '1';
						}
						postData(url, param)
							.then((res) => {
								ElMessage.success(res.msg || '保存成功');
								this.saveFormLoading = false;
							})
							.finally(() => {
								this.saveFormLoading = false;
							});
					} else {
						let message = '';
						if (fields && Object.keys(fields).length > 0) {
							let field = fields[Object.keys(fields)[0]];
							let messages = field.map((item) => {
								return item.message;
							});
							message = messages.join(',');
						}
						ElMessage.error('验证未通过！' + message);
						console.log('error submit!', fields);
					}
				});
			},
			resetForm() {
				if (!this.$refs.formRef) return;
				this.$refs.formRef.resetFields();
			}
		},
		async mounted() {
			this.router = useRouter();
			this.globalOption = useRoute().query;
			const stores = useUserInfo();
			const { userInfos } = storeToRefs(stores);
			this.userInfo = userInfos;
			await this.init();
			this.editFormInit = deepClone(this.editForm);
			this.queryParamsInit = deepClone(this.queryParams);
			this.handleQuery();
			this.mittBus.on('onEditAdmintableModule', () => {
				this.handleQuery();
			});
		},
		beforeUnmount() {
			this.mittBus.off('onEditAdmintableModule');
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep {
	}
	.flex-clz {
		padding-top: 5px;
		padding-left: 0px;
		padding-bottom: 5px;
		padding-right: 0px;
	}
	.text4-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.text2-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.text6-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.flex3-clz {
		padding-top: 5px;
		padding-left: 0px;
		padding-bottom: 5px;
		padding-right: 0px;
	}
	.text-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.flex7-clz {
		padding-top: 5px;
		padding-left: 0px;
		padding-bottom: 5px;
		padding-right: 0px;
	}
	.text8-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.flex10-clz {
		margin-left: 0px;
		border: 1px solid #eee;
		border-bottom-left-radius: 6px;
		overflow: hidden;
		width: calc(100% - 0px - 10px) !important;
		border-top-left-radius: 6px;
		margin-top: 0px;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		margin-bottom: 0px;
		margin-right: 10px;
	}
	.image-clz {
		margin-left: 5px;
		border-bottom-left-radius: 6px;
		overflow: hidden;
		border-top-left-radius: 6px;
		margin-top: 5px;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		margin-bottom: 5px;
		margin-right: 5px;
	}
	.flex11-clz {
		padding-top: 5px;
		padding-left: 5px;
		padding-bottom: 5px;
		padding-right: 5px;
	}
	.flex9-clz {
		padding-top: 5px;
		padding-left: 0px;
		padding-bottom: 5px;
		padding-right: 0px;
	}
	.text9-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.flex13-clz {
		padding-top: 5px;
		padding-left: 0px;
		padding-bottom: 5px;
		padding-right: 0px;
	}
	.text11-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.text15-clz {
		flex-shrink: 0;
		padding-top: 5px;
		padding-left: 5px;
		width: 90px !important;
		padding-bottom: 5px;
		text-align: right;
		padding-right: 10px;
	}
	.flex6-clz {
		padding-top: 5px;
		padding-left: 5px;
		padding-bottom: 5px;
		padding-right: 5px;
	}
	.button-clz {
		margin-left: 5px;
		border-bottom-left-radius: 6px;
		overflow: hidden;
		border-top-left-radius: 6px;
		margin-top: 5px;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		margin-bottom: 5px;
		margin-right: 5px;
	}
	.button2-clz {
		margin-left: 5px;
		border-bottom-left-radius: 6px;
		overflow: hidden;
		border-top-left-radius: 6px;
		margin-top: 5px;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		margin-bottom: 5px;
		margin-right: 5px;
	}
	.button1-clz {
		margin-left: 5px;
		border-bottom-left-radius: 6px;
		overflow: hidden;
		border-top-left-radius: 6px;
		margin-top: 5px;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		margin-bottom: 5px;
		margin-right: 5px;
	}
	.container {
		font-size: 12px;
	}
</style>
